package com.song.controller;

import com.song.pojo.UploadFile;
import com.song.service.FileService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    //服务器根路径
    private String Path="D:\\qiyuesuo\\";

    @Autowired
    FileService fileService;

    private final Logger logger =  Logger.getLogger(getClass());

    //上传文件
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String Upload(HttpServletRequest request, HttpServletResponse response){
        String uuid = UUID.randomUUID().toString();
        Date time = new Date();
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
        String today = sdf.format(time);
        InputStream is = null;
        FileOutputStream fos=null;
        File files = new File(Path+"\\"+today);
        if (!files.exists()){
            //创建文件夹，如果父文件夹不存在，就会创建父文件夹
            files.mkdirs();
            logger.info("创建文件夹成功");
        }

        File file = new File( Path+today+"\\"+uuid+"."+(request.getHeader("type")));
        try {
            //接收客户端传来的文件流
            is = request.getInputStream();

            // 复制文件
            fos = new FileOutputStream(file);
            byte b[] = new byte[1024];
            int length = 0;
            while (-1 != (length = is.read(b))) {
                fos.write(b, 0, length);
            }
            logger.info("上传文件成功");
            long size = Long.parseLong((request.getHeader("size")));
            String type = request.getHeader("type");
            String oldName = request.getHeader("oldName");
            java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis());
            String url = Path+today+"\\"+uuid+"."+(request.getHeader("type"));

            UploadFile uploadFile = new UploadFile(size,type,oldName,currentDate,url,uuid);
            fileService.addFile(uploadFile);
            logger.info("文件信息保存成功");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return uuid;
    }

    //下载文件
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public void Download(HttpServletRequest request, HttpServletResponse response){
        UploadFile uploadfile = fileService.findByUuid(request.getHeader("uuid"));
        logger.info("uuid: "+request.getHeader("uuid"));
        File f=new File(uploadfile.getUrl());
        response.setHeader("oldName",uploadfile.getOldName());
        try {
            InputStream in=new FileInputStream(f);
            OutputStream out=new DataOutputStream(response.getOutputStream());
            byte[] b=new byte[1024];
            int length = 0;
            while (-1 != (length = in.read(b))){
                out.write(b,0,length);
            }
            in.close();
            out.close();
            logger.info("文件下载成功");
        } catch (IOException e) {
            response.setStatus(401);
            logger.info("文件不存在");
            e.printStackTrace();
        }
    }

    //获取元数据
    @RequestMapping(value = "/findByUuid", method = RequestMethod.GET)
    @ResponseBody
    public UploadFile getInfo(String uuid){
        UploadFile uploadFile = fileService.findByUuid(uuid);

        return uploadFile;
    }
}
